//import 'package:amap_base/amap_base.dart';

import 'dart:async';
import 'dart:convert';
import 'dart:developer';

import 'package:barcode_scan/barcode_scan.dart';
import 'package:date_format/date_format.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bmfmap/BaiduMap/models/bmf_map_options.dart';
import 'package:flutter_hotwork/HomePage.dart';
import 'package:flutter_hotwork/Myapplication.dart';
import 'package:flutter_hotwork/bean/BaseBean.dart';
import 'package:flutter_hotwork/bean/xunjian/guijilistbean.dart';
import 'package:flutter_hotwork/bean/xunjian/ticketslistbean.dart';
import 'package:flutter_hotwork/homepage/BaseTitleBar.dart';
import 'package:flutter_hotwork/homepage/BaseViewBar.dart';
import 'package:flutter_hotwork/utils/DioUtils.dart';
import 'package:flutter_hotwork/xunjian/XunJianEnd.dart';
import 'package:flutter_hotwork/zhifa/QuestionEdit.dart';
// import 'package:flutter_hotwork/xunjian/wentishangbao.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong/latlong.dart';
import 'package:flutter_bmfbase/BaiduMap/bmfmap_base.dart';
import 'package:flutter_bmfmap/BaiduMap/bmfmap_map.dart';
import 'package:flutter_bmflocation/bdmap_location_flutter_plugin.dart';
import 'package:flutter_bmflocation/flutter_baidu_location.dart';
import 'package:flutter_bmflocation/flutter_baidu_location_android_option.dart';
import 'package:flutter_bmflocation/flutter_baidu_location_ios_option.dart';
import 'dart:math';
import '../LoadingDialog.dart';
import '../Login.dart';
import '../Toast.dart';
import 'XunJianWenTiShangBao.dart';

class Xunjian2Page extends StatefulWidget {
  @override
  Xunjian2State createState() => new Xunjian2State();
}
Map<String, Object> _loationResult;
BaiduLocation _baiduLocation; // 定位结果
StreamSubscription<Map<String, Object>> _locationListener;
LocationFlutterPlugin _locationPlugin = new LocationFlutterPlugin();
int firstlocation=0;
Size screenSize;
Timer mtimer;
double latitude = MyApplication.latitude;
double longitude = MyApplication.longitude;
List<BMFCoordinate> coordinates = List();
List<BMFCoordinate> coordinatestickets = List();
var newtime=formatDate(new DateTime.now(),[yyyy,'-',mm,'-',dd ,"  ",HH,":",nn,":",ss]);
guijilistbean guijilist;
ticketslistbean ticketslist;

int  hasdata = 0;
class Xunjian2State extends State<Xunjian2Page> {
  Xunjian2State();
  BMFMapController myMapController;
  /// 纹理索引
  List<int> indexs = [0, 0, 0, 0];

  /// 纹理集合
  List<String> textures = List(4);


  @override
  void initState() {
    super.initState();
    DioUtils.createInstance();
  }

  @override
  void dispose() {
    hasdata=0;
    firstlocation=0;
    coordinates = List();
    coordinatestickets = List();
    if (null != _locationListener) {
      _locationListener.cancel(); // 停止定位
    }
    mtimer.cancel();  // 取消定时器
    super.dispose();
  }

  /// 设置android端和ios端定位参数
  void _setLocOption() {
    /// android 端设置定位参数
    BaiduLocationAndroidOption androidOption = new BaiduLocationAndroidOption();
    androidOption.setCoorType("bd09ll"); // 设置返回的位置坐标系类型
    androidOption.setIsNeedAltitude(true); // 设置是否需要返回海拔高度信息
    androidOption.setIsNeedAddres(true); // 设置是否需要返回地址信息
    androidOption.setIsNeedLocationPoiList(true); // 设置是否需要返回周边poi信息
    androidOption.setIsNeedNewVersionRgc(true); // 设置是否需要返回最新版本rgc信息
    androidOption.setIsNeedLocationDescribe(true); // 设置是否需要返回位置描述
    androidOption.setOpenGps(true); // 设置是否需要使用gps
    androidOption.setLocationMode(LocationMode.Hight_Accuracy); // 设置定位模式
    androidOption.setScanspan(2000); // 设置发起定位请求时间间隔

    Map androidMap = androidOption.getMap();

    /// ios 端设置定位参数
    BaiduLocationIOSOption iosOption = new BaiduLocationIOSOption();
    iosOption.setIsNeedNewVersionRgc(true); // 设置是否需要返回最新版本rgc信息
    iosOption.setBMKLocationCoordinateType("BMKLocationCoordinateTypeBMK09LL"); // 设置返回的位置坐标系类型
    iosOption.setActivityType("CLActivityTypeAutomotiveNavigation"); // 设置应用位置类型
    iosOption.setLocationTimeout(10); // 设置位置获取超时时间
    iosOption.setDesiredAccuracy("kCLLocationAccuracyBest");  // 设置预期精度参数
    iosOption.setReGeocodeTimeout(10); // 设置获取地址信息超时时间
    iosOption.setDistanceFilter(100); // 设置定位最小更新距离
    iosOption.setAllowsBackgroundLocationUpdates(true); // 是否允许后台定位
    iosOption.setPauseLocUpdateAutomatically(true); //  定位是否会被系统自动暂停

    Map iosMap = iosOption.getMap();

    _locationPlugin.prepareLoc(androidMap, iosMap);
  }

  /// 启动定位
  void _startLocation() {
    if (null != _locationPlugin) {
      _setLocOption();
      _locationPlugin.startLocation();
    }
  }

  /// 停止定位
  void _stopLocation() {
    if (null != _locationPlugin) {
      _locationPlugin.stopLocation();
    }
  }





  /// 创建mapView回调
  BMFMapOptions mapOptions = BMFMapOptions(
      center: BMFCoordinate(latitude, longitude),
      zoomLevel: 18,
      mapPadding: BMFEdgeInsets(left: 30, top: 0, right: 30, bottom: 0));

  /// 创建完成回调
  void onBMFMapCreated(BMFMapController controller) {
    myMapController = controller;

    if(hasdata==0){
      getpointList();
    }

    /// 地图加载回调
    myMapController?.setMapDidLoadCallback(callback: () {
      print('mapDidLoad-地图加载完成');
    });

    // /// 创建BMFMarker
    // BMFMarker marker = BMFMarker(
    //     position: BMFCoordinate(MyApplication.latitude, MyApplication.longitude),
    //     title: 'flutterMaker',
    //     identifier: 'flutter_marker',
    //     icon: 'images/icon_end.png');


    myMapController?.showUserLocation(true);

    BMFCoordinate coordinate = BMFCoordinate(latitude, longitude);

    BMFLocation location = BMFLocation(
        coordinate: coordinate,
        altitude: 0,
        horizontalAccuracy: 5,
        verticalAccuracy: -1.0,
        speed: -1.0,
        course: -1.0);

    BMFUserLocation userLocation = BMFUserLocation(
      location: location,
    );

    myMapController?.updateLocationData(userLocation);

    // BMFUserlocationDisplayParam displayParam = BMFUserlocationDisplayParam(
    //     locationViewOffsetX: 0,
    //     locationViewOffsetY: 0,
    //     accuracyCircleFillColor: Colors.red,
    //     accuracyCircleStrokeColor: Colors.blue,
    //     isAccuracyCircleShow: true,
    //     locationViewImage: 'images/weizhi.png',
    //     locationViewHierarchy:
    //     BMFLocationViewHierarchy.LOCATION_VIEW_HIERARCHY_BOTTOM);
    //
    // myMapController?.updateLocationViewWithParam(displayParam);
    /// 添加Marker
    // myMapController.addMarker(marker);

    textures[0] = 'images/traffic_texture_smooth.png';
    textures[1] = 'images/traffic_texture_slow.png';
    textures[2] = 'images/traffic_texture_unknown.png';
    textures[3] = 'images/traffic_texture_smooth.png';
    /// 创建polyline
    BMFPolyline texturesPolyline = BMFPolyline(
      // id: polylineOptions.hashCode.toString(),
        coordinates: coordinates,
        indexs: indexs,
        textures: textures,
        width: 16,
        dottedLine: true,
        lineDashType: BMFLineDashType.LineDashTypeNone,
        lineCapType: BMFLineCapType.LineCapButt,
        lineJoinType: BMFLineJoinType.LineJoinRound);

    /// 添加polyline
    myMapController?.addPolyline(texturesPolyline);



  }

//获取轨迹
  void getpointList() async {
    // Navigator.pop(context);
    try {
      Response response;
      response = await DioUtils.dio.get(
          DioUtils.API_PREFIX + "/checkGis/listCheckGis?checkId="+MyApplication.nowtaskbean.id.toString());
      Map respMap = json.decode(response.data);
      guijilist = guijilistbean.fromJson(respMap);
      hasdata+=1;

      setState(() {

        try{
          myMapController?.setCenterCoordinate(bd_encrypt(
              guijilist.result[0].checkGisPos[guijilist.result[0].checkGisPos.length-1].lat,
              guijilist.result[0].checkGisPos[guijilist.result[0].checkGisPos.length-1].lon), true,
              animateDurationMs: 1000);
        }catch(e){

        }
        for(int i = 0;i<guijilist.result.length;i++){
          if(guijilist.result[i].checkUser==MyApplication.loginuserinfo.userInfo.username){
            for(int j = 0;j<guijilist.result[i].checkGisPos.length;j++){
              try {
                if(MyApplication.nowtaskbean.taskStatus==2) {
                  // 延时1s执行返回
                  Future.delayed(Duration(milliseconds: 100), () {
                    coordinates.add(bd_encrypt(
                        guijilist.result[i].checkGisPos[j].lat,
                        guijilist.result[i].checkGisPos[j].lon));
                    if (coordinates.length > 1) {
                      BMFPolyline texturesPolyline = BMFPolyline(
                        // id: polylineOptions.hashCode.toString(),
                          coordinates: coordinates,
                          indexs: indexs,
                          textures: textures,
                          width: 16,
                          dottedLine: true,
                          lineDashType: BMFLineDashType.LineDashTypeNone,
                          lineCapType: BMFLineCapType.LineCapButt,
                          lineJoinType: BMFLineJoinType.LineJoinRound);

                      /// 添加polyline
                      myMapController?.addPolyline(texturesPolyline);
                    }

                    print('延时0.1s执行');
                  });
                }else{
                  coordinates.add(bd_encrypt(
                      guijilist.result[i].checkGisPos[j].lat,
                      guijilist.result[i].checkGisPos[j].lon));

                  if (coordinates.length > 1) {
                    BMFPolyline texturesPolyline = BMFPolyline(
                      // id: polylineOptions.hashCode.toString(),
                        coordinates: coordinates,
                        indexs: indexs,
                        textures: textures,
                        width: 16,
                        dottedLine: true,
                        lineDashType: BMFLineDashType.LineDashTypeNone,
                        lineCapType: BMFLineCapType.LineCapButt,
                        lineJoinType: BMFLineJoinType.LineJoinRound);

                    /// 添加polyline
                    myMapController?.addPolyline(texturesPolyline);
                  }
                }

              }catch(e){
                print('解析出错：' + e.toString());
              }
            }
          }
        }
        /// 创建polyline
        gettickList();

      });

    } catch (e) {
      print('请求出错：' + e.toString());
    }
  }

  //获取打卡点
  void gettickList() async {
    // Navigator.pop(context);
    try {
      Response response;
      response = await DioUtils.dio.get(
          DioUtils.API_PREFIX + "/clockIn/listClockIn?checkId="+MyApplication.nowtaskbean.id.toString());
      Map respMap = json.decode(response.data);
      ticketslist = ticketslistbean.fromJson(respMap);
      hasdata+=1;
      for(int i = 0;i<ticketslist.result.length;i++){
        coordinatestickets.add(bd_encrypt(ticketslist.result[i].lat, ticketslist.result[i].lon));
      }
      List<BMFMarker> markers = new List();
      for(int i = 0 ;i<coordinatestickets.length;i++){
        /// 创建BMFMarker
        BMFMarker marker = BMFMarker(
            position: coordinatestickets[i],
            title: '打卡',
            identifier: '打卡',
            icon: 'images/takepoint.png');
        markers.add(marker);
      }
      setState(() {
      myMapController.addMarkers(markers);
      });
    } catch (e) {
      print('请求出错：' + e.toString());
    }
  }
  //  扫描二维码


  @override
  Widget build(BuildContext context) {
    if(hasdata==0){

      _startLocation();
      if (_loationResult != null) {
        _loationResult.forEach((key, value) {
          if(key == "latitude"){
            latitude=value;
            MyApplication.latitude = value;
          }
          if(key == "locationDetail"){
            MyApplication.locationdetail=value;
          }
          if(key == "longitude"){
            longitude=value;
            MyApplication.longitude = value;
          }
        });
        if(MyApplication.nowtaskbean.taskStatus!=2) {

          if(null!=latitude){
            coordinates.add(BMFCoordinate(latitude, longitude));
            uploadxy(latitude, longitude);
          }

        }
      }
    }

    screenSize = MediaQuery.of(context).size;
    const timeout = const Duration(seconds: 30);
    if(firstlocation==0&&MyApplication.nowtaskbean.taskStatus!=2){
      /// 动态申请定位权限
      _locationPlugin.requestPermission();
      /// 设置ios端ak, android端ak可以直接在清单文件中配置
      LocationFlutterPlugin.setApiKey("AATp1fIh3jcs3nUN4wglXGzG209ZQZap");
      _locationListener = _locationPlugin
          .onResultCallback()
          .listen((Map<String, Object> result) {
        setState(() {
          _loationResult = result;
          try {
            _baiduLocation = BaiduLocation.fromMap(result); // 将原生端返回的定位结果信息存储在定位结果类中
//          print(_baiduLocation);
          } catch (e) {
            print(e);
          }
        });
      });
      firstlocation=1;
      mtimer=new  Timer.periodic(timeout, (mtimer) { //callback function
        //1s 回调一次
        _startLocation();
        if (_loationResult != null) {
          _loationResult.forEach((key, value) {
            if(key == "latitude"){
              latitude=value;
              MyApplication.latitude = value;
            }
            if(key == "locationDetail"){
              MyApplication.locationdetail=value;
            }
            if(key == "longitude"){
              longitude=value;
              MyApplication.longitude = value;
            }
          });
          if(null!=latitude){
            coordinates.add(BMFCoordinate(latitude, longitude));
            uploaduserxy(latitude,longitude);
            uploadxy(latitude,longitude);
          }

        }

      });
    }

    return

      Scaffold(

          appBar: new BaseViewBar(
              childView: new BaseTitleBar(
                "智能巡检",
                leftIcon: 'images/fanhui.png',
                rightIcon: "",
                rightClick: () {
                  // Navigator.push(context, MaterialPageRoute(builder: (context) {
                  //   return new BasicLoc();
                  // }));
                },
                leftClick: () {
                  Navigator.of(context).pop();
                  print("点击了左边干嘛啊。。。哦");
                },
              ),
              preferredSize: Size.fromHeight(50.0)),
          body:
          new SingleChildScrollView(
            child: new ConstrainedBox(
                constraints: new BoxConstraints(
                  minHeight: 120.0,
                ),


          child:new Column(
              children: [

                Container(
                  height:
                  MyApplication.nowtaskbean.taskStatus==2?screenSize.height-74:
                  screenSize.height-240,
                  width: screenSize.width,
                  child: BMFMapWidget(
                    onBMFMapCreated: (controller) {
                      onBMFMapCreated(controller);
                    },
                    mapOptions: mapOptions,
                  ),
                ),
                MyApplication.nowtaskbean.taskStatus==2?Container():
                Column(
                    children: [
                      Container(child:
                      Text("正在记录巡检管线")
                        ,),
                      Container(
                        margin: EdgeInsets.only(left: 0,top: 2,right: 0,bottom: 2),
                        height: 0.5,
                        color: Colors.grey[300],
                        width: screenSize.width-40,
                      ),
                      Container(child:
                      Text("巡检开始时间    "+(MyApplication.nowtaskbean.taskStatus==0?newtime:MyApplication.nowtaskbean.checkStartTime))
                        ,),
                      Container(
                        margin: EdgeInsets.only(left: 0,top: 2,right: 0,bottom: 2),
                        height: 0.5,
                        color: Colors.grey[300],
                        width: screenSize.width-40,
                      ),
                      Container(child:
                      Text("最新轨迹时间    $newtime")
                        ,),
                      Container(
                        margin: EdgeInsets.only(left: 0,top: 2,right: 0,bottom: 2),
                        height: 0.5,
                        color: Colors.grey[300],
                        width: screenSize.width-40,
                      ),

                      Container(
                        margin: EdgeInsets.only(left: 0,top: 5,right: 0,bottom: 0),
                        child:
                        Row(
                          mainAxisAlignment:MainAxisAlignment.center,
                          children: [
                            InkWell(
                              onTap: (){
                                Navigator.push(context, MaterialPageRoute(builder: (context) {
                                  return new XunJianEditScreen();
                                }));
                              },
                              child:
                              Image(height:70,width: 70,image: AssetImage('images/wentishangbao.png')),
                            ),


                            Container(width: 20,),
                            InkWell(
                              onTap: (){
                                scan();
                              },
                              child:
                              Image(height:70,width: 70,image: AssetImage('images/daka.png')),
                            ),

                            Container(width: 20,),
                            InkWell(
                              onTap: (){
                                Navigator.push(context, MaterialPageRoute(builder: (context) {
                                  return new XunJianEndScreen();
                                }));
                              },
                              child:
                              Image(height:70,width: 70,image: AssetImage('images/jieshuxunjian.png')),
                            )
                          ],
                        )
                        ,
                      )
                    ])     ,
              ])
            ),
        // :Container()
         )
      );
  }

  // //结束巡检
  // void uptask(var id,var status) async {
  //   var reqeuest =Map<Object,Object>();
  //   reqeuest["id"] = id;
  //   reqeuest["checkUser"] = MyApplication.loginuserinfo.userInfo.username;
  //   try {
  //     Response response;
  //     response = await DioUtils.dio.put(DioUtils.API_PREFIX+"/checkTask/overCheckTaskById", data: json.encode(reqeuest));
  //
  //     Map respMap = json.decode(response.data);
  //     basebean base = basebean.fromJson(respMap);
  //     print('响应数据：' + response.toString());
  //     if(base.code==0){
  //       LocalToast.toast(context,msg:"结束巡检成功！");
  //     }
  //   } catch (e) {
  //     LocalToast.toast(context,msg:"结束巡检失败！");
  //     print('请求出错：' + e.toString());
  //   }
  // }
  //实时上传轨迹
  void uploadxy(var latitude,var longitude) async {
    var reqeuest =Map<Object,Object>();
    reqeuest["lat"] = bd_decrypt(latitude,longitude).latitude;
    reqeuest["lon"] = bd_decrypt(latitude,longitude).longitude;
    reqeuest["checkUser"] = MyApplication.loginuserinfo.userInfo.username;
    reqeuest["checkUserName"] = MyApplication.loginuserinfo.userInfo.realname;
    reqeuest["checkId"] = MyApplication.nowtaskbean.id;
    reqeuest["createTime"] = new DateTime.now().toString();
    newtime=formatDate(new DateTime.now(),[yyyy,'-',mm,'-',dd ,"  ",HH,":",nn,":",ss]);
    try {
      Response response;
      response = await DioUtils.dio.post(DioUtils.API_PREFIX+"/checkGis/insertCheckGis", data: json.encode(reqeuest));

      Map respMap = json.decode(response.data);
      basebean base = basebean.fromJson(respMap);
      setState(() {
        /// 创建polyline
        if(coordinates.length>1){
          BMFPolyline texturesPolyline = BMFPolyline(
            // id: polylineOptions.hashCode.toString(),
              coordinates: coordinates,
              indexs: indexs,
              textures: textures,
              width: 16,
              dottedLine: true,
              lineDashType: BMFLineDashType.LineDashTypeNone,
              lineCapType: BMFLineCapType.LineCapButt,
              lineJoinType: BMFLineJoinType.LineJoinRound);

          /// 添加polyline
          myMapController?.addPolyline(texturesPolyline);
        }

      });

      print('响应数据：' + response.toString());
    } catch (e) {
      print('请求出错：' + e.toString());
    }
  }

  //实时上传轨迹
  void uploaduserxy(var latitude,var longitude) async {
    var reqeuest =Map<Object,Object>();
    reqeuest["lat"] = bd_decrypt(latitude,longitude).latitude;
    reqeuest["longitude"] = bd_decrypt(latitude,longitude).longitude;
    reqeuest["userId"] = MyApplication.loginuserinfo.userInfo.id;
    reqeuest["userName"] = MyApplication.loginuserinfo.userInfo.realname;
    reqeuest["taskId"] = MyApplication.nowtaskbean.id;
    reqeuest["taskName"] = MyApplication.nowtaskbean.lineName;
    newtime=formatDate(new DateTime.now(),[yyyy,'-',mm,'-',dd ,"  ",HH,":",nn,":",ss]);
    try {
      Response response;
      response = await DioUtils.dio.post(DioUtils.API_PREFIX+"/gis/addRealTimePosition", data: json.encode(reqeuest));

      Map respMap = json.decode(response.data);
      basebean base = basebean.fromJson(respMap);

      print('响应数据：' + response.toString());
    } catch (e) {
      print('请求出错：' + e.toString());
    }
  }
  //上传打卡点
  void uploadticket(var clockInNumber) async {
    showDialog(
        context: context,
        builder: (context) {
          return new LoadingDialog();
        });
    var reqeuest =Map<Object,Object>();
    reqeuest["lat"] = bd_decrypt(latitude,longitude).latitude;
    reqeuest["lon"] = bd_decrypt(latitude,longitude).longitude;
    reqeuest["clockInNumber"] = clockInNumber;
    reqeuest["checkId"] = MyApplication.nowtaskbean.id;
    reqeuest["clockTime"] = new DateTime.now().toString();
    try {
      Response response;
      response = await DioUtils.dio.post(DioUtils.API_PREFIX+"/clockIn/insertClockIn", data: json.encode(reqeuest));

      Map respMap = json.decode(response.data);
      basebean base = basebean.fromJson(respMap);
      Navigator.pop(context);
      if(base.code==0){
        coordinatestickets.add(BMFCoordinate(latitude, longitude));
        LocalToast.toast(context,msg: "打卡成功");
        setState(() {
          BMFMarker marker = BMFMarker(
              position: BMFCoordinate(latitude, longitude),
              title: '打卡',
              identifier: '打卡',
              icon: 'images/takepoint.png')
          ;
          myMapController.addMarker(marker);

        });
      } else if(base.code == 500){
        LocalToast.toast(context,msg:"会话超时，请重新登陆！");
        Navigator.pushAndRemoveUntil(
          context,
          new MaterialPageRoute(
              builder: (context) => new MyHomePage()),
              (route) => route == null,
        );
      }
      print('响应数据：' + response.toString());
    } catch (e) {
      Navigator.pop(context);
      LocalToast.toast(context,msg: "打卡失败");
    }
  }

  BMFCoordinate bd_encrypt(double gg_lat, double gg_lon) {

    var X_PI = pi * 3000.0 / 180.0;
    double x = gg_lon, y = gg_lat;

    double z = sqrt(x * x + y * y) + 0.00002 * sin(y * X_PI);

    double theta = atan2(y, x) + 0.000003 * cos(x * X_PI);

    double bd_lon = z * cos(theta) + 0.0065;

    double bd_lat = z * sin(theta) + 0.006;


    return new BMFCoordinate(bd_lat, bd_lon);
  }
//百度坐标转高德（传入经度、纬度）
  BMFCoordinate bd_decrypt(bd_lat, bd_lng) {
    var X_PI = pi * 3000.0 / 180.0;
    var x = bd_lng - 0.0065;
    var y = bd_lat - 0.006;
    var z = sqrt(x * x + y * y) - 0.00002 * sin(y * X_PI);
    var theta = atan2(y, x) - 0.000003 * cos(x * X_PI);
    var gg_lng = z * cos(theta);
    var gg_lat = z * sin(theta);
    return new BMFCoordinate(gg_lat, gg_lng);
  }

  Future scan() async {
    try {
      // 此处为扫码结果，barcode为二维码的内容
      String barcode = await BarcodeScanner.scan();
      print('扫码结果: '+barcode);
      uploadticket(barcode);
    } on PlatformException catch (e) {
      if (e.code == BarcodeScanner.CameraAccessDenied) {
        // 未授予APP相机权限
        print('未授予APP相机权限');
      } else {
        // 扫码错误
        print('扫码错误: $e');
      }
    } on FormatException{
      // 进入扫码页面后未扫码就返回
      print('进入扫码页面后未扫码就返回');
    } catch (e) {
      // 扫码错误
      print('扫码错误: $e');
    }
  }
}






















